const api = require("../config/api")
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

function request(url, data = {}, method = "GET", header = {'Content-Type': 'application/json'}) {

    return new Promise(function(resolve, reject) {
        header["X-MiniProgram-Token"] = wx.getStorageSync('token');
      wx.request({
        url: url,
        data: data,
        method: method,
        header: header,
        success: function(res) {
  
          if (res.statusCode == 200) {
  
            if (res.data.errno == 501) {
              // 清除登录相关内容
              try {
                wx.removeStorageSync('logined')
                wx.removeStorageSync('token');
              } catch (e) {
                // Do something when catch error
              }
              // 切换到登录页面
              isLogin(function (){

              });
            } else {
              resolve(res.data);
            }
          } else {
            if (res.statusCode == 403 || res.statusCode == 400){
                // 清除登录相关内容
              try {
                wx.removeStorageSync('logined')
                wx.removeStorageSync('token');
              } catch (e) {
                // Do something when catch error
              }
              // 切换到登录页面
              isLogin(function (){

              });
              reject("登录有效期已过，请重新登录");
            }else{
                reject("服务器开小差了，请联系管理员!");
            }

          }
  
        },
        fail: function(err) {
          reject(err)
        }
      })
    });
  }

  function isLogin(callback){
      let logined = wx.getStorageSync('logined');
      if (!logined){
          wx.showModal({
            title: '提示',
            content: '请先授权登录',
            confirmText:"登录",
            complete: (res) => {
              if (res.cancel) {
                
              }
          
              if (res.confirm) {
                    //获取推荐商户id
                    let merchantId = null;
                    let role = null;
                    wx.getStorage({
                      key: 'merchantId',
                      success: (res) => {
                        console.log('merchantId:', res.data); // 输出存储的值
                        merchantId = res.data;
                      },
                      fail: (err) => {
                        console.error('读取失败:', err);
                      }
                    });
                    wx.getStorage({
                      key: 'role',
                      success: (res) => {
                        console.log('role:', res.data); // 输出存储的值
                        role = res.data;
                      },
                      fail: (err) => {
                        console.error('读取失败:', err);
                      }
                    });
                    wx.getUserProfile({
                      desc: '用于获取用户信息',
                      success:(res) => {
                        let detail = res;

                        wx.login({
                            success: (res) => {
                              if (res.code){
                                  wx.showLoading();
                                  request(api.AuthLoginByWeixin, {
                                     code:res.code,
                                     weixinFullVO:detail,
                                     merchantId:merchantId,
                                     role:role
                                  }, 'POST').then(res => {
                                      wx.hideLoading();

                                      if (res.code == "0"){
                                        wx.setStorageSync('token', res.data.token);
                                        wx.setStorageSync('logined', true);
                                        callback();
                                      }else{
                                            wx.showToast({
                                              title: res.message,
                                              icon:"none"
                                            })
                                      }
                                  })
                              }
                            },
                            fail: (e) => {
                                wx.showToast({
                                  title: 'e',
                                  icon:"none"
                                })
                            }
                          })
                      }
                    })

              }
            }
          })
      }else{
            callback();
      }
  }

function isVip(callback){
    wx.showLoading();
    request(api.getUserInfo, {}, "POST").then(function (res){
        wx.hideLoading();
        if (res.code == 0){
            if (res.data.vip_status == 1){
                wx.showModal({
                    title: '提示',
                    content: '请激活VIP后操作',
                    complete: (res) => {
                      if (res.cancel) {
                        
                      }
                      if (res.confirm) {
                          wx.navigateTo({
                            url: '/pages/home/vip/vip',
                          })
                      }
                    }
                  })
            }else{
                callback();
            }
        }else{
            wx.showToast({
              title: res.message,
              icon:"none"
            })
        }
    }).catch(function (e){
        wx.hideLoading();
        wx.showToast({
          title: e,
          icon:"none"
        })
    })


}



/**
 * 通用确认框
 * @param {Object} options 配置选项
 * @param {String} options.title 标题
 * @param {String} options.content 提示内容
 * @param {String} options.confirmText 确定按钮文字，默认"同意"
 * @param {String} options.cancelText 取消按钮文字，默认"取消"
 * @param {Function} options.onConfirm 确定回调函数
 * @param {Function} options.onCancel 取消回调函数
 */
function showConfirmModal(options = {}) {
  const {
    title = '提示',
    content = '请确认操作',
    confirmText = '同意',
    cancelText = '取消',
    onConfirm = () => {},
    onCancel = () => {}
  } = options;

  // 获取当前页面实例
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  
  // 动态引入公共样式
  const stylePath = '/styles/confirmModal.wxss';
  try {
    // 尝试引入公共样式（如果页面没有引入过）
    if (!currentPage._confirmModalStyleLoaded) {
      // 这里可以通过动态创建style标签来引入样式
      // 或者要求页面手动引入样式文件
      currentPage._confirmModalStyleLoaded = true;
    }
  } catch (e) {
    console.warn('Failed to load confirm modal styles:', e);
  }
  
  // 设置页面数据，显示确认框
  currentPage.setData({
    showConfirmModal: true,
    confirmModalConfig: {
      title,
      content,
      confirmText,
      cancelText
    }
  });

  // 绑定事件处理函数到页面实例
  currentPage.handleConfirmModalConfirm = function() {
    currentPage.setData({ showConfirmModal: false });
    if (typeof onConfirm === 'function') {
      onConfirm();
    }
  };

  currentPage.handleConfirmModalCancel = function() {
    currentPage.setData({ showConfirmModal: false });
    if (typeof onCancel === 'function') {
      onCancel();
    }
  };

  // 返回控制对象
  return {
    close: () => {
      currentPage.setData({ showConfirmModal: false });
    },
    update: (newOptions) => {
      const updatedConfig = { ...currentPage.data.confirmModalConfig, ...newOptions };
      currentPage.setData({
        confirmModalConfig: updatedConfig
      });
    }
  };
}

module.exports = {
  formatTime,
  isVip,
  isLogin,
  request,
  showConfirmModal
}
